package com.cqie.rbac.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cqie.rbac.entity.SysUser;
import com.cqie.rbac.vo.UserVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Set;

/**
 * <p>
 * 用户实体 Mapper 接口
 * </p>
 *
 * @author 夏兵
 * @since 2021-09-02
 */
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {

    /**
     * 分页查询用户信息
     *
     * @param page         分页信息
     * @param queryWrapper 查询条件
     * @return 用户信息集合
     */
    @Select({"<script>", "SELECT DISTINCT\n" +
            "\tsu.id,\n" +
            "\tsu.`name`,\n" +
            "\tsu.`account`,\n" +
            "\tsu.`status`,\n" +
            "\tsu.create_time,\n" +
            "\t(\n" +
            "\tSELECT\n" +
            "\t\tGROUP_CONCAT( sr.`name` ) \n" +
            "\tFROM\n" +
            "\t\tsys_role sr\n" +
            "\t\tLEFT JOIN user_role ur ON sr.id = ur.role_id \n" +
            "\tWHERE\n" +
            "\t\tur.user_id = su.id \n" +
            "\t\tAND sr.`status` = 0 \n" +
            "\t) role \n" +
            "FROM\n" +
            "\tsys_user su\n" +
            "\tLEFT JOIN user_role ur ON su.id = ur.user_id\n" +
            "<if test=\"ew.sqlSegment != null and ew.sqlSegment != ''\">\n" +
            "AND ${ew.sqlSegment}\n" +
            "</if>" +
            "GROUP BY su.id", "</script>"})
    IPage<UserVo> selectPage(IPage<UserVo> page,
                             @Param("ew") QueryWrapper<UserVo> queryWrapper);

    /**
     * 根据用户id查询用户信息
     *
     * @param id 用户id
     * @return 用户信息
     */
    @Select({"<script>", "SELECT\n" +
            "\t su.id,\n" +
            "\t su.`name`,\n" +
            "\t su.`status`,\n" +
            "\t su.password," +
            "\t GROUP_CONCAT( sr.id ) as role \n" +
            "FROM\n" +
            "\t sys_user su\n" +
            "\t LEFT JOIN user_role ur ON su.id = ur.user_id\n" +
            "\t LEFT JOIN sys_role sr ON ur.role_id = sr.id \n" +
            "WHERE\n" +
            "\tsu.id =${id} AND sr.status = 0", "</script>"})
    UserVo queryUserById(@Param("id") Long id);

    /**
     * 查询用户拥有的权限码
     * @param uId 用户id
     * @return 权限码集合
     */
    @Select("SELECT DISTINCT\n" +
            "\tsm.permission_code \n" +
            "FROM\n" +
            "\tsys_user su\n" +
            "\tLEFT JOIN user_role ur ON su.id = ur.user_id\n" +
            "\tLEFT JOIN sys_role sr ON ur.role_id = sr.id\n" +
            "\tLEFT JOIN role_menu rm ON ur.role_id = rm.role_id\n" +
            "\tJOIN sys_menu sm ON rm.menu_id = sm.id \n" +
            "WHERE\n" +
            "\tsu.id = ${uId} \n" +
            "\tAND sr.`status` = 0")
    Set<String> queryUserPermissionCode(@Param("uId") Long uId);
}
